﻿///<reference path="../jquery-1.4.4.min.js" />
///<reference path="kooboo.js"/>
///<reference path="validator/kooboo.validators.greaterthan.js"/>
///<reference path="validator/kooboo.validators.lessthan.js"/>
///<reference path="validator/kooboo.validators.stringlength.js"/>
///<reference path="validator/kooboo.validators.regularexpression.js"/>
///<reference path="validator/kooboo.validators.required.js"/>
///<reference path="validator/kooboo.validators.number.js"/>



//$.fn.serializeAnything = function () {
//    var data = [];
//    var elements = $(this).find(':input').get();

//    $.each(elements, function () {
//        if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) {
//            var val = $(this).val();
//            data.push(encodeURIComponent(this.name) + "=" + encodeURIComponent(val));
//        }
//    });
//    return data.join("&").replace(/%20/g, "+");

//}

$.fn.mvcvalidate = function (data, invalidHandler, formId) {


    var isValid = true;

    if (typeof window.mvcClientValidationMetadata == "undefined") {
        return true;
    }

    var isValid = true;
    var formAction = null;

    var element = $(this);
    if (element.is("form")) {
        formAction = formAction || element.attr("action");
        data = data || element.serialize();
    } else if (element.is("a")) {
        formAction = formAction || element.attr("href");
        data = data || "";
    } else {
        data = data || $("*", element).serialize();
    }


    if (formAction) {
        formAction = formAction.toLowerCase();
    }

    formId = formId || element.attr("id") || element.attr("name")



    $.fn.mvcvalidate.defaults.cleanError(element);

    var metadata = null;

    for (var i = 0; i < window.mvcClientValidationMetadata.length; i++) {
        var item = window.mvcClientValidationMetadata[i];
        if (item) {
            if (item.FormAction.toLowerCase() == formAction || item.FormId == formId) {
                metadata = item;
                break;
            }
        }
    }
    if (metadata != null) {
        invalidHandler = invalidHandler || $.fn.mvcvalidate.defaults.showError;
        var values = {};
        var items = data.split("&");
        for (var i in items) {
            var pair = items[i].split("=");
            if (pair) {
                if (pair.length > 1) {
                    values[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
                } else {
                    values[decodeURIComponent([0])] = null;
                }
            }
        }


        var strict = element.attr("strict") ? true : false;
        for (var i in metadata.Fields) {
            var field = metadata.Fields[i];
            for (var fieldName in values) {
                if (matchName(fieldName, field.FieldName, strict)) {
                    for (var m in field.ValidationRules) {
                        var rule = field.ValidationRules[m];
                        if (kooboo.validators[rule.ValidationType](values[fieldName], rule.ValidationParameters) == false) {
                            isValid = false;
                            invalidHandler("[name=\"" + fieldName + "\"]", rule.ErrorMessage, element);
                            break;

                        };
                    }
                }
            }
        }
    }

    $.fn.mvcvalidate.defaults.complete(isValid, element);
    return isValid;

    function matchName(source, target, strict) {
        if (strict === true) {
            return source == target;
        } else {
            if (target == null || target == "" || source.length == 0 || target.length > source.length) {
                return false;
            }
            if (source.substring(source.length - target.length) == target) {
                return true;
            } else {
                return false;
            }

            return true;
        }
    }
}

$.fn.cleanError = function () {
    $.fn.mvcvalidate.defaults.cleanError($(this));
    return this;
}

$.fn.mvcvalidate.defaults = {
    showError: function (selector, error, form) {

        var region = form || document;
        var target = $(selector, region);
        if (target.size() > 0) {
            var label = $("<span></span>").addClass("field-validation-error").attr("selector", selector).html(error);
            label.insertAfter(target);

            var cleanInvalid = function () {
                var sender = $(this);
                var count = parseInt(sender.attr("data-invalid-error-count"));
                var next = sender.next();
                if (next.is(".field-validation-error")) {
                    next.remove();
                }               

                sender.removeAttr("data-invalid-error-count");
                
                $(sender).unbind("change", cleanInvalid);
            }

            target.change(cleanInvalid);

          
        }

    },
    cleanError: function (form) {
        var region = form || document;
        $(".field-validation-error", region).remove();
    },
    complete: function (isValid, form) {
    }
}


